<template>
    <div class="vab-app-main">
        <section>
            <transition mode="out-in" name="fade-transform">
                <vab-keep-alive v-if="routerView"/>
            </transition>
        </section>
    </div>
</template>

<script lang="ts">
import VabProgress from 'nprogress'
import BaseVue from "@/common/base-vue";
import {Component, Watch} from 'vue-property-decorator';
import {RouterActionsEnum, SettingsGetterEnum, TabsGetterEnum} from '@/store/enum/store.enum';
import VabKeepAlive from '@/vab/components/VabKeepAlive'

@Component({components: {VabKeepAlive}})
export default class VabAppMain extends BaseVue {
    private routerView: boolean = true;

    get settings() {
        return {
            theme: this.$store.getters[SettingsGetterEnum.theme],
            extra: this.$store.getters[SettingsGetterEnum.extra],
            visitedRoutes: this.$store.getters[TabsGetterEnum.visitedRoutes],
        }
    };

    get changeData() {
        return [
            ...new Set(
                this.settings.visitedRoutes.filter((item) =>
                    !item.meta.noKeepAlive &&
                    item.name !== this.settings.extra.transferRouteName
                ).flatMap((item) => item.matched)
            ),
        ]
    };

    @Watch('changeData', {})
    handler(visitedRoutes) {
        this.setCachedRoutes(visitedRoutes);
    };

    created() {
        const {showProgressBar} = this.settings.theme;
        // 单页面情况下重载路由
        this.$bus.$on('reload-router-view', () => {
            this.routerView = false;
            if (showProgressBar) VabProgress.start()
            this.$nextTick(() => {
                this.routerView = true;
                setTimeout(() => {
                    if (showProgressBar) VabProgress.done();
                }, 200)
            })
        })
    };

    private setCachedRoutes(val: object[]) {
        this.$store.commit(RouterActionsEnum.setCachedRoutes, val)
    }
}
</script>
